<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="设备名称">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="属性名称">
        <el-input
          v-model="queryParams.propertyName"
          placeholder="请输入属性名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报警类型">
        <el-select
          v-model="queryParams.alarmKind"
          clearable
          placeholder="请选择报警类型"
          style="width: 160px"
        >
          <el-option
            v-for="opt in alarmKindOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="openEdit()"
          v-hasPermi="['alarm:alarmRule:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Search" @click="toggleSearch">{{
          showSearch ? "隐藏搜索" : "显示搜索"
        }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Refresh" @click="fetchList"
          >刷新</el-button
        >
      </el-col>
    </el-row>

    <el-card shadow="never">
      <el-table :data="tableData" v-loading="loading" style="height: 630px">
        <el-table-column prop="alarmKind" label="报警类型" width="120">
          <template #default="{ row }">{{
            getAlarmKindName(row.alarmKind)
          }}</template>
        </el-table-column>
        <el-table-column prop="alarmLevel" label="报警等级" width="120" />
        <el-table-column prop="groupName" label="用能单元" width="140" />
        <el-table-column prop="deviceName" label="设备名称" width="130" />
        <el-table-column prop="propertyName" label="属性名称" width="130" />
        <el-table-column prop="compareType" label="比较类型" width="120">
          <template #default="{ row }">{{
            getCompareTypeName(row.compareType)
          }}</template>
        </el-table-column>
        <el-table-column prop="maxThreshold" label="上限值" width="100" />
        <el-table-column prop="minThreshold" label="下限值" width="100" />
        <el-table-column prop="dataType" label="业务类型" width="120">
          <template #default="{ row }">{{
            getDataTypeName(row.dataType)
          }}</template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column prop="enabled" label="是否启用" width="100">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'danger'" size="small">
              {{ row.enabled ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="messageTemplate"
          label="消息模板"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="openEdit(row)"
              v-hasPermi="['alarm:alarmRule:edit']"
              >编辑</el-button
            >
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
              v-hasPermi="['alarm:alarmRule:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          :current-page="pager.pageNum"
          :page-size="pager.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="onPageChange"
          @size-change="onSizeChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="720px"
      append-to-body
      destroy-on-close
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="报警类型" prop="alarmKind">
              <el-select v-model="form.alarmKind" placeholder="请选择">
                <el-option
                  v-for="opt in alarmKindOptions"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.alarmKind === ALARM_KIND.BUSINESS">
            <el-form-item label="业务类型" prop="dataType">
              <el-select v-model="form.dataType" placeholder="请选择">
                <el-option
                  v-for="opt in dataTypeOptions"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="报警等级" prop="alarmLevel">
              <el-select v-model="form.alarmLevel" placeholder="请选择">
                <el-option
                  v-for="lvl in alarmLevelOptions"
                  :key="lvl.value"
                  :label="lvl.label"
                  :value="lvl.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <!-- 综合能耗：可选择设备 -->
          <el-col
            :span="12"
            v-if="
              form.alarmKind === ALARM_KIND.BUSINESS &&
              form.dataType === DATA_TYPE.ENERGY
            "
          >
            <el-form-item label="设备" prop="deviceId">
              <el-select
                v-model="form.deviceId"
                filterable
                placeholder="请选择设备"
                @change="handleDeviceChange"
              >
                <el-option
                  v-for="dev in deviceOptions"
                  :key="dev.id"
                  :label="dev.deviceName || dev.name"
                  :value="dev.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 指标报警：可选择设备和设备属性 -->
          <el-col :span="12" v-if="form.alarmKind === ALARM_KIND.INDICATOR">
            <el-form-item label="设备" prop="deviceId">
              <el-select
                v-model="form.deviceId"
                filterable
                placeholder="请选择设备"
                @change="handleDeviceChange"
              >
                <el-option
                  v-for="dev in deviceOptions"
                  :key="dev.id"
                  :label="dev.deviceName || dev.name"
                  :value="dev.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.alarmKind === ALARM_KIND.INDICATOR">
            <el-form-item label="设备属性" prop="dataPropertyId">
              <el-select
                v-model="form.dataPropertyId"
                filterable
                placeholder="请选择设备属性"
                :loading="propertyLoading"
                @change="handlePropertyChange"
              >
                <el-option
                  v-for="prop in deviceProperties"
                  :key="prop.id"
                  :label="prop.name"
                  :value="prop.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 碳排放量和费用总量：可选择用能单元 -->
          <el-col
            :span="12"
            v-if="
              form.alarmKind === ALARM_KIND.BUSINESS &&
              (form.dataType === DATA_TYPE.CARBON ||
                form.dataType === DATA_TYPE.COST)
            "
          >
            <el-form-item label="用能单元" prop="groupId">
              <el-tree-select
                v-model="form.groupId"
                :data="unitTreeData"
                check-strictly
                node-key="value"
                :props="{ label: 'label', children: 'children' }"
                placeholder="请选择用能单元"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="比较类型" prop="compareType">
              <el-select v-model="form.compareType" placeholder="请选择">
                <el-option
                  v-for="opt in compareTypeOptions"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 指标报警和业务报警的阈值设置 -->
        <el-row :gutter="16" v-if="form.alarmKind !== ALARM_KIND.OFFLINE">
          <el-col
            :span="12"
            v-if="
              form.compareType === COMPARE_TYPE.MAX ||
              form.compareType === COMPARE_TYPE.MAX_MIN
            "
          >
            <el-form-item label="上限值" prop="maxThreshold">
              <el-input-number
                v-model="form.maxThreshold"
                :precision="2"
                style="width: 100%"
                placeholder="请输入上限值"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="12"
            v-if="
              form.compareType === COMPARE_TYPE.MIN ||
              form.compareType === COMPARE_TYPE.MAX_MIN
            "
          >
            <el-form-item label="下限值" prop="minThreshold">
              <el-input-number
                v-model="form.minThreshold"
                :precision="2"
                style="width: 100%"
                placeholder="请输入下限值"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.compareType === COMPARE_TYPE.RANGE">
            <el-form-item label="区间上限" prop="maxThreshold">
              <el-input-number
                v-model="form.maxThreshold"
                :precision="2"
                style="width: 100%"
                placeholder="请输入区间上限"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.compareType === COMPARE_TYPE.RANGE">
            <el-form-item label="区间下限" prop="minThreshold">
              <el-input-number
                v-model="form.minThreshold"
                :precision="2"
                style="width: 100%"
                placeholder="请输入区间下限"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 设备离线报警的阈值设置 -->
        <el-row :gutter="16" v-if="form.alarmKind === ALARM_KIND.OFFLINE">
          <el-col :span="12">
            <el-form-item label="上限值(分钟)" prop="maxThreshold">
              <el-input-number
                v-model="form.maxThreshold"
                :precision="0"
                style="width: 100%"
                placeholder="请输入离线时间上限(分钟)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下限值(分钟)" prop="minThreshold">
              <el-input-number
                v-model="form.minThreshold"
                :precision="0"
                style="width: 100%"
                placeholder="请输入离线时间下限(分钟)"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="报警内容" prop="messageTemplate">
          <el-input
            type="textarea"
            v-model="form.messageTemplate"
            :rows="2"
            placeholder="请输入报警内容模板"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" :rows="2" />
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-switch
            v-model="form.enabled"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: right">
          <el-button
            type="primary"
            @click="handleSubmit"
            v-hasPermi="['alarm:alarmRule:save']"
            >保 存</el-button
          >
          <el-button @click="dialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import {
  listAlarmRules,
  submitAlarmRule,
  deleteAlarmRules,
} from "@/api/alarm/alarmRules";
import { getAlarmLevelList } from "@/api/alarm/alarmLevel";
import { listEnergyUnit } from "@/api/deviceManage/energyUnit";
import { getDeviceList } from "@/api/deviceManage/device";
import { getDeviceRealtimeData } from "@/api/stat/realtime";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  ALARM_KIND,
  ALARM_KIND_OPTIONS,
  COMPARE_TYPE,
  COMPARE_TYPE_OPTIONS,
  DATA_TYPE,
  DATA_TYPE_OPTIONS,
  getAlarmKindName,
  getCompareTypeName,
  getDataTypeName,
} from "@/utils/alarmConstants";

const { proxy } = getCurrentInstance();

const loading = ref(false);
const tableData = ref([]);
const total = ref(0);
const pager = reactive({ pageNum: 1, pageSize: 10 });

const queryParams = reactive({
  deviceName: "",
  propertyName: "",
  alarmKind: undefined,
});

const alarmKindOptions = ALARM_KIND_OPTIONS;
const compareTypeOptions = COMPARE_TYPE_OPTIONS;
const dataTypeOptions = DATA_TYPE_OPTIONS;

// 下拉、树数据
const alarmLevelOptions = ref([]);
const unitTreeData = ref([]);
const deviceOptions = ref([]);
const deviceProperties = ref([]);
const propertyLoading = ref(false);

// 搜索显隐
const showSearch = ref(true);

// 表单
const dialogVisible = ref(false);
const dialogTitle = ref("新增报警规则");
const formRef = ref();
const form = reactive({
  id: null,
  alarmKind: undefined,
  alarmLevel: undefined,
  groupId: undefined,
  groupName: "",
  deviceId: undefined,
  deviceName: "",
  dataPropertyId: undefined,
  propertyName: "",
  compareType: COMPARE_TYPE.MAX, // 默认上限报警
  threshold: 0,
  maxThreshold: 0,
  minThreshold: 0,
  dataType: DATA_TYPE.ENERGY, // 默认综合能耗
  messageTemplate: "",
  remark: "",
  enabled: 1,
});
const rules = {
  alarmKind: [{ required: true, message: "请选择报警类型", trigger: "change" }],
  alarmLevel: [
    { required: true, message: "请选择报警等级", trigger: "change" },
  ],
  deviceId: [
    {
      required: true,
      message: "请选择设备",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (
          form.alarmKind === ALARM_KIND.INDICATOR ||
          (form.alarmKind === ALARM_KIND.BUSINESS &&
            form.dataType === DATA_TYPE.ENERGY)
        ) {
          if (!value) {
            callback(new Error("请选择设备"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
    },
  ],
  dataPropertyId: [
    {
      required: true,
      message: "请选择设备属性",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (form.alarmKind === ALARM_KIND.INDICATOR && !value) {
          callback(new Error("请选择设备属性"));
        } else {
          callback();
        }
      },
    },
  ],
  groupId: [
    {
      required: true,
      message: "请选择用能单元",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (
          form.alarmKind === ALARM_KIND.BUSINESS &&
          (form.dataType === DATA_TYPE.CARBON ||
            form.dataType === DATA_TYPE.COST) &&
          !value
        ) {
          callback(new Error("请选择用能单元"));
        } else {
          callback();
        }
      },
    },
  ],
  dataType: [
    {
      required: true,
      message: "请选择业务类型",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (form.alarmKind === ALARM_KIND.BUSINESS && !value) {
          callback(new Error("请选择业务类型"));
        } else {
          callback();
        }
      },
    },
  ],
  compareType: [
    { required: true, message: "请选择比较类型", trigger: "change" },
  ],
  threshold: [{ required: true, message: "请输入判断值", trigger: "blur" }],
  maxThreshold: [{ required: true, message: "请输入上限值", trigger: "blur" }],
  minThreshold: [{ required: true, message: "请输入下限值", trigger: "blur" }],
};

function transformUnitTree(list) {
  if (!Array.isArray(list)) return [];
  return list.map((n) => ({
    label: n.label,
    value: n.id,
    children: transformUnitTree(n.children || []),
  }));
}

function loadOptions() {
  getAlarmLevelList().then((res) => {
    const arr = res.data?.list || [];
    alarmLevelOptions.value = arr.map((i) => ({
      label: i.name,
      value: i.code,
    }));
  });
  listEnergyUnit().then((res) => {
    unitTreeData.value = transformUnitTree(res.data || []);
  });
  getDeviceList({ pageNum: 1, pageSize: 1000 }).then((res) => {
    deviceOptions.value = res.data?.list || [];
  });
}

// 处理设备变化
function handleDeviceChange(deviceId) {
  if (!deviceId) {
    deviceProperties.value = [];
    form.dataPropertyId = undefined;
    form.propertyName = "";
    return;
  }

  // 清空之前的属性选择
  form.dataPropertyId = undefined;
  form.propertyName = "";

  // 加载设备属性
  loadDeviceProperties(deviceId);
}

// 加载设备属性
function loadDeviceProperties(deviceId) {
  if (!deviceId) return;

  propertyLoading.value = true;
  getDeviceRealtimeData(deviceId)
    .then((response) => {
      if (response.data && response.data.proPertyList) {
        // 只取 kind 为 1 的数据属性
        deviceProperties.value = response.data.proPertyList.filter(
          (prop) => prop.kind === 1
        );
      } else {
        deviceProperties.value = [];
      }
    })
    .catch((error) => {
      console.error("获取设备属性失败:", error);
      deviceProperties.value = [];
    })
    .finally(() => {
      propertyLoading.value = false;
    });
}

// 处理属性变化
function handlePropertyChange(dataPropertyId) {
  if (!dataPropertyId) {
    form.propertyName = "";
    return;
  }

  const selectedProperty = deviceProperties.value.find(
    (prop) => prop.id === dataPropertyId
  );
  if (selectedProperty) {
    form.propertyName = selectedProperty.name;
  }
}

function fetchList() {
  loading.value = true;
  listAlarmRules({
    ...queryParams,
    pageNum: pager.pageNum,
    pageSize: pager.pageSize,
  })
    .then((res) => {
      tableData.value = res.data?.list || res.rows || [];
      // 兼容 totalCount 返回
      total.value = res.data?.totalCount ?? res.data?.total ?? res.total ?? 0;
    })
    .finally(() => (loading.value = false));
}

function handleQuery() {
  pager.pageNum = 1;
  fetchList();
}
function resetQuery() {
  queryParams.deviceName = "";
  queryParams.propertyName = "";
  queryParams.alarmKind = undefined;
  handleQuery();
}

function toggleSearch() {
  showSearch.value = !showSearch.value;
}
function onPageChange(p) {
  pager.pageNum = p;
  fetchList();
}
function onSizeChange(s) {
  pager.pageSize = s;
  pager.pageNum = 1;
  fetchList();
}

function openEdit(row) {
  if (row) {
    dialogTitle.value = "编辑报警规则";
    Object.assign(form, row);
    // 兼容后端主键字段 ruleId
    if (row.ruleId) form.id = row.ruleId;

    // 确保数字类型字段正确回显
    form.dataType = row.dataType || DATA_TYPE.ENERGY;
    form.groupId = row.groupId || undefined;
    form.deviceId = row.deviceId || undefined;
    form.dataPropertyId = row.dataPropertyId || undefined;
    form.alarmKind = row.alarmKind;
    form.alarmLevel = row.alarmLevel;
    form.compareType = row.compareType || COMPARE_TYPE.MAX;

    // 如果是编辑且是指标报警，需要加载设备属性
    if (form.alarmKind === ALARM_KIND.INDICATOR && form.deviceId) {
      loadDeviceProperties(form.deviceId);
    }
  } else {
    dialogTitle.value = "新增报警规则";
    Object.assign(form, {
      id: null,
      alarmKind: undefined,
      alarmLevel: undefined,
      groupId: undefined,
      deviceId: undefined,
      dataPropertyId: undefined,
      propertyName: "",
      compareType: COMPARE_TYPE.MAX,
      threshold: 0,
      maxThreshold: 0,
      minThreshold: 0,
      dataType: DATA_TYPE.ENERGY,
      messageTemplate: "",
      remark: "",
      enabled: 1,
    });
  }

  // 清空设备属性列表
  deviceProperties.value = [];
  dialogVisible.value = true;
}

function handleSubmit() {
  formRef.value.validate((valid) => {
    if (!valid) return;
    submitAlarmRule(form).then(() => {
      ElMessage.success("保存成功");
      dialogVisible.value = false;
      fetchList();
    });
  });
}

function handleDelete(row) {
  ElMessageBox.confirm(`确认删除该规则?`, "提示", { type: "warning" }).then(
    () => {
      const key = row.ruleId || row.id;
      deleteAlarmRules([key]).then(() => {
        ElMessage.success("删除成功");
        fetchList();
      });
    }
  );
}

onMounted(() => {
  loadOptions();
  fetchList();
});
</script>

<style scoped lang="scss">
.app-container {
  padding: 10px 20px;
  background: #f1f2f5;
  height: 100%;
  overflow-y: auto;
}

// 搜索表单样式（对齐报警等级页）
.el-form {
  background: #ffffff;
  padding: 10px 20px;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .el-button {
    border-radius: 6px;
    font-weight: 500;

    &.el-button--primary {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }

    &:not(.el-button--primary) {
      background: linear-gradient(135deg, #909399 0%, #73767a 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #82848a 0%, #6c6e72 100%);
        color: #ffffff;
      }
    }
  }
}

// 顶部按钮组
.mb8 {
  margin-bottom: 10px;
  margin-left: 0 !important;
  margin-right: 0 !important;
  background: #ffffff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .el-button {
    border-radius: 6px;
    font-weight: 500;
  }
}

// 表格样式
.main-table {
  width: 100%;
}

// 分页样式
::v-deep(.el-pagination) {
  margin-top: 20px;
  text-align: center;
}
</style>
